package com.blqy.fr.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.blqy.fr.common.annotation.BlQyLogin;
import com.blqy.fr.common.execption.BlQyException;
import com.blqy.fr.common.result.ResultCodeEnum;
import com.blqy.fr.common.util.AuthContextHolder;
import com.blqy.fr.model.user.Team;
import com.blqy.fr.model.user.TeamUser;
import com.blqy.fr.model.user.User;
import com.blqy.fr.user.mapper.TeamInfoMapper;
import com.blqy.fr.user.mapper.TeamUserMapper;
import com.blqy.fr.user.service.TeamInfoService;
import com.blqy.fr.vo.team.TeamDetailVo;
import com.blqy.fr.vo.team.TeamVo;
import com.blqy.fr.vo.user.UserMyVo;
import com.blqy.fr.vo.user.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class TeamInfoServiceImpl implements TeamInfoService {

    @Autowired
    private TeamInfoMapper teamInfoMapper;

    @Autowired
    private TeamUserMapper teamUserMapper;


    @Transactional
    @BlQyLogin
    @Override
    public TeamVo getOrCreateDefaultTeam() {

        Long userId = AuthContextHolder.getUserId();
        if (userId == null) {
            throw new BlQyException(ResultCodeEnum.LOGIN_AUTH);
        }

        // 1. 查询用户已加入的任意一个团队
        List<Team> userTeams = teamInfoMapper.selectTeamsByUserId(userId);
        Team existingTeam = userTeams.isEmpty() ? null : userTeams.get(0);

        if (existingTeam != null) {
            // 已有团队，直接返回
            TeamVo teamVo = new TeamVo();
            BeanUtils.copyProperties(existingTeam, teamVo);
            teamVo.setTeamId(existingTeam.getId()); // 假设 BaseEntity 有 id
            return teamVo;
        }

        // 2. 没有团队，创建默认团队
        Team newTeam = new Team();
        newTeam.setTeamName("诈骗团队");
        newTeam.setDaily(1);
        newTeam.setWeekly(0);
        newTeam.setMonthly(0);
        newTeam.setIsHoliday(0);
        newTeam.setTeamSize(1L);

        // 设置体验期：1天后过期
        Date expireTime = Date.from(
                LocalDateTime.now().plusDays(1)
                        .atZone(ZoneId.systemDefault())
                        .toInstant()
        );
        newTeam.setExperienceTime(expireTime);

        // 插入团队
        teamInfoMapper.insert(newTeam); // 确保 insert 后 newTeam 的 id 被回填

        // 3. 创建 team_user 关联记录
        TeamUser teamUser = new TeamUser();
        teamUser.setUserId(userId);
        teamUser.setTeamId(newTeam.getId());
        teamUserMapper.insert(teamUser);

        // 4. 返回新团队信息
        TeamVo teamVo = new TeamVo();
        BeanUtils.copyProperties(newTeam, teamVo);
        teamVo.setTeamId(newTeam.getId());
        return teamVo;
    }

    @BlQyLogin
    @Override
    public TeamDetailVo findMyTeam() {
        Long userId = AuthContextHolder.getUserId();
        if (userId == null) {
            throw new BlQyException(ResultCodeEnum.LOGIN_AUTH);
        }

        // 通过 userId 查找 team_user
        TeamUser teamUser = teamUserMapper.selectOne(
                new LambdaQueryWrapper<TeamUser>()
                        .eq(TeamUser::getUserId, userId)
                        .eq(TeamUser::getIsDeleted, 0)
        );

        if (teamUser == null) {
            throw new BlQyException(ResultCodeEnum.TEAM_NOT_EXIST);
        }

        Team team = teamInfoMapper.selectById(teamUser.getTeamId());
        if (team == null || team.getIsDeleted() == 1) {
            throw new BlQyException(ResultCodeEnum.TEAM_NOT_EXIST);
        }

        List<UserMyVo> members = teamUserMapper.selectMembersByTeamId(team.getId());

        TeamDetailVo vo = new TeamDetailVo();
        vo.setTeamId(team.getId());
        vo.setTeamName(team.getTeamName());
        vo.setExperienceTime(team.getExperienceTime());
        vo.setTeamSize((long) members.size());
        vo.setMembers(members);

        return vo;
    }

}
